require 'rubygems'
require 'RMagick'
require 'check_quantity_callback'
include Magick
include ImagePath

class Design < ActiveRecord::Base
  has_and_belongs_to_many :categories
  has_many :prints
  #  before_save  :remove_background
  after_save :resize
  before_save :convert_categories_array,CheckQuantityCallback.new(:quantity)
  attr_accessor :categories_array
  validates_numericality_of :height,:width,:quantity
  validates_presence_of :height,:width
  file_column :image_url, :magick => {:versions => { "thumb" => "90X90",
      "medium" => "130X130","overlay"=>"450X480","origin"=>"800X800"}}

  PROPORTION = 450.0/70.0


  TYPES = [
    [ "前中图",   "fm" ],
    [ "后中图",   "bm" ],
    [ "左胸图",   "lu" ],
    [ "前右下",   "frd" ],
    [ "前左下",   "fld" ],
    [ "后右下",   "brd" ]
  ]

  MALE = 1
  FEMALE = 0
  NEUTRAL = 2

  SEX = [
    [ "适合男生", MALE ],
    [ "适合女生", FEMALE ],
    [ "男女皆可", NEUTRAL]

  ]
  
  def self.recommend_list
    self.find(:all,:conditions=>{:active=>1,:recommend=>1},:limit=>6)
  end

  def remove_background(geometry_size,thumb_size)
    img = ImageList.new(self.detail_image_url1)
    thumb_path = File.dirname(self.image_url("thumb"))
    geometry_path = File.dirname(self.image_url)
    file_name = File.basename(self.image_url)
    #  Dir.mkdir(thumb_path,0775) if !File.exist?(thumb_path)
    #  Dir.mkdir(medium_path,0775) if !File.exist?(medium_path)
    img.trim!(true)
    img.background_color = '#fff'
    img.border!(0,0,'none')
    #    
    img.resize_to_fit!("234X196")
    img.write(geometry_path + '/'  + file_name)
    img.resize_to_fit!("90X90")
    img.border!(90/2,90/2,'none')
    img.crop!(CenterGravity,90,90)
    img.write(thumb_path + '/'  + file_name)
    #  img.write(medium_path + '/'  + file_name
  end

  def resize
    return if !self.height || !self.width
    geometry_path = File.dirname(self.image_url)
    file_name = File.basename(self.image_url)
    if File.exist?(self.image_url("origin"))
      img = ImageList.new(self.image_url("origin"))
      img.thumbnail!(self.width * PROPORTION,self.height * PROPORTION)
      img.write(geometry_path + '/'  + file_name)
    end
  end

  def first_category_id
    return if !self.categories.find(:first)
    self.categories.find(:first).id
  end

  

  private
  def convert_categories_array
    return if !categories_array
    self.categories.clear

    for item_hash in categories_array.values
      #chech_box没有选中的时候，提交的值为"0"
      if item_hash.values[0] !="0"
        category = Category.find(item_hash.values[0])
        self.categories << category
      end
    end
  end
end


